<?php

namespace App\Http\Controllers\Api;

use App\Libraries\Error;
use App\Models\Company;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use App\Models\Employee;
use App\Models\SmsCode;
use App\Models\User;
use Firebase\JWT\JWT;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;
use Illuminate\Support\Facades\DB;

class MiniLoginController extends ApiController
{

    protected $redirectTo = '/';


    public function isregister(Request $request) {
        $mobile = $request->mobile;
        $user = User::where('mobile',$mobile)->where('status',1)->first();
        $is_register = 2;
        if ($user) {
            $is_register = 1;
        }

        return showError(Error::ERR_OK,['is_register'=>$is_register]);
    }

    public function getcompany(Request $request)
    {
        // 搜索内容
        $where = [];
        $company_name = $request->input('company_name');
        if (!empty($company_name))
        {
            $where['company_name'] = $company_name;
        }

        $where['status'] = 1;

        $list = Company::getList($where);

        return showError(Error::ERR_OK,['list'=>$list]);
    }

    //手机号、验证码登陆
    public function Login(Request $request) {

        $mobile  = $request->mobile;
        $mobileCode = $request->mobileCode;
//        $this->validate($request, [
//            'mobile' => 'bail|required',
//            'mobileCode' => 'bail|required',
//        ]);
        if (empty($mobile)) {
            return showError(Error::ERR_ERROR, null, "无效的手机号");
        }

        $userInfo = Employee::where('mobile',$mobile)->where('status',1)->first();
        if(empty($userInfo)){
            return showError(Error::ERR_NO_EMPLOYEE);
        }

        if (!empty($mobileCode)) {
            $codeinfo = SmsCode::where('mobile',$mobile)->orderBy('id','desc')->get();

            if((isset($codeinfo[0]['code']) && $mobileCode == $codeinfo[0]['code'])) {
                //生成token
                $time = time();
                $payload = [
                    'iat' => $time,  //签发时间
                    'nbf' => $time,  //时间点后才能访问
                    'exp' => $time + 2629743, //过期时间 一个月
                    'data' => $userInfo,
                ];
                $token = JWT::encode($payload, env('JWT_KEY'));

                return showError(Error::ERR_OK,[ 'token' => $token ],"登陆成功");
            }else{
                return showError(Error::ERR_ERROR,"","手机验证码错误");
            }
        }


    }

    public function sendSms(Request $request){
        $mobile = $request->mobile;
        $userInfo = Employee::where('mobile',$mobile)->where('status',1)->first();
        if(empty($userInfo)){
            return showError(Error::ERR_NO_EMPLOYEE);
        }
        try {
            $code = rand(1000,9999);
            $data = array(
                'code' => $code,
                'mobile' => $mobile,
                'extra' => 'minilogin',
                'result' => 1,
                'ctime' => time(),
                'mtime' => time(),
            );
            SmsCode::create($data);
            $res = $this->sendMessage($mobile,$code);
            if($res['Code'] == 'OK'){
                return showError(Error::ERR_OK,'','验证码已发送');
            }else{
                return showError(Error::ERR_SYSTEM_ERROR,'','验证码发送失败');
            }

        } catch (Exception $e) {

        }
    }

    /**
     * 发送验证码
     *
     * $mobile  @ 手机号 多个逗号分隔
     * $number  @ 验证码号
     */
    protected function sendMessage($mobile, $number){

        AlibabaCloud::accessKeyClient(env('accessKeyId'), env('accessSecret'))
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumbers' => $mobile,
                        'SignName'=>env('MESSAGE_SIGN'),
                        'TemplateCode'=>env('TemplateCode'),//todo 换模板
                        'TemplateParam'=>json_encode(["code"=>$number])
                    ],
                ])
                ->request();

            return $result->toArray();
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }

    }

    public function post_data_curl($url, $data, $isMulitArray = 0) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_TIMEOUT, 180);

        curl_setopt($ch, CURLOPT_POST, 1);
        if ($isMulitArray) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        } else {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }

        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output, true);
        return $output;
    }

    /**
     * 微信登录
     */
    public function wechatLogin(Request $request)
    {
        $code = $request->code;
        $encryptedData = $request->encryptedData;
        $iv = $request->iv;
        if(empty($code)){
            return showError(Error::ERR_ERROR, null, "无效的code!");
        }

        $oauth = $this->getOauth($code);
        $data = [];
        if(isset($oauth['session_key'])) {
            $data = $this->decryptWXdata($encryptedData,$oauth['session_key'],$iv);
            $data = json_decode($data,true);
            if (!$data) {
                $data = $this->decryptWXdata($encryptedData,$oauth['session_key'],$iv);
                $data = json_decode($data,true);
                if (!$data) {
                    $data = $this->decryptWXdata($encryptedData,$oauth['session_key'],$iv);
                    $data = json_decode($data,true);
                }
            }
        }

        if(!$data){
            return showError(Error::ERR_ERROR, null, "授权异常，请再试一次");
        }
        $openId = isset($oauth['openid'])?$oauth['openid']:'';
        $mobile = isset($data['phoneNumber'])?$data['phoneNumber']:'';

        $userInfo = Employee::where('mobile',$mobile)->where('status',1)->first();
        if(empty($userInfo)){
            return showError(Error::ERR_NO_EMPLOYEE);
        }

        //更新user表 手机号
       Employee::where('mobile',$mobile)->where('status',1)->update(['open_id'=>$openId]);
        //生成token
        $time = time();
        $payload = [
            'iat' => $time,  //签发时间
            'nbf' => $time,  //时间点后才能访问
            'exp' => $time + 2629743, //过期时间 一个月
            'data' => $userInfo,
        ];
        $token = JWT::encode($payload, env('JWT_KEY'));

        return showError(Error::ERR_OK,['mobile'=>$mobile, 'token' => $token ],"登陆成功");

    }

    //获取授权
    private function getOauth($code){
        $url='https://api.weixin.qq.com/sns/jscode2session?appid='.env('MINI_APP_ID').'&secret='.env('MINI_APP_SECRET').'&js_code='.$code.'&grant_type=authorization_code';
        $accessRes = $this->post_data_curl($url, [], 1);
//        ErrorSvc::writeLog(ErrorSvc::ERR_ERROR, print_r($accessRes,true), "peakview_miniapplogin");
        return $accessRes;
    }

    private  function decryptWXdata($encryptedData, $sessionKey, $iv)
    {
        //微信传输的三个参数都是base64编码过的，所以函数内对三项参数都做了base64_decode
        return openssl_decrypt(base64_decode($encryptedData),'aes-128-cbc',base64_decode($sessionKey),OPENSSL_RAW_DATA,base64_decode($iv));
    }

//    //更新用户信息
//    public function userInfo(Request $request) {
//        if (!$request->token) {
//            return showError(Error::ERR_ERROR, null, "无效的token!");
//        }
//        $userInfo = JWT::decode($request->token,env('JWT_KEY'), array('HS256'));
//        $exp = $userInfo->exp;
//        if (time() > $exp) {
//            return showError(Error::ERR_TOKEN_ERROR);
//        }
//        $userInfo = (array)$userInfo->data;
//        $uid = $userInfo['uid'];
//        $user = Employee::where('uid',$uid)->where('status',1)->first();
//        if (empty($user)) {
//            return showError(Error::ERR_TOKEN_ERROR);
//        }
////        $uid = '29221';
//        $data = [
//            'username' => $request->nickName,
//            'nickname' => $request->nickName,
//            'gender'   => $request->gender,
//            'city'     => $request->city,
//            'province' => $request->province,
//            'country'  => $request->country,
//            'avatar'   => $request->avatarUrl,
//        ];
//        Employee::where('uid',$uid)->update($data);
//        return showError(Error::ERR_OK);
//
//    }

    /**
     * 是否绑定信息
     */
    public function isbind(Request $request)
    {
        if (!$request->token) {
            return showError(Error::ERR_ERROR, null, "无效的token!");
        }
        $userInfo = JWT::decode($request->token,env('JWT_KEY'), array('HS256'));
        $exp = $userInfo->exp;
        if (time() > $exp) {
            return showError(Error::ERR_TOKEN_ERROR);
        }
        $userInfo = (array)$userInfo->data;
        $employee_id = $userInfo['employee_id'];
        $user = Employee::where('employee_id',$employee_id)->where('status',1)->first();
        if (empty($user)) {
            return showError(Error::ERR_TOKEN_ERROR);
        }
        $is_user_mobile = 2;
        if (!empty($user['mobile'])) {
            $is_user_mobile = 1;
        }


        return showError(Error::ERR_OK,['is_user_mobile'=>$is_user_mobile,"mobile"=>$user['mobile']]);
    }



}
